<template>
  <view class="content">
    <h-form :labelWidth="180" :model="model" :rules="rules" ref="form">
      <h-form-item label="头像" class="item" prop="avatarUrl">
            <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
              <image class="avatarUrl" :src="model.avatarUrl" />
            </button>
      </h-form-item>
      <h-form-item label="昵称" class="item" prop="nickName">
          <h-input type="nickname" @blur="handleNickName" v-model="model.nickName" placeholder="获取昵称"/>
      </h-form-item>
      <h-form-item label="性别" class="item" prop="sex">
          <h-picker :selector="actions" v-model="model.sex"></h-picker>
      </h-form-item>
      <h-form-item label="年龄" class="item" prop="age">
          <h-input type="number" v-model="model.age" placeholder="请填写年龄"></h-input>
      </h-form-item>
      <h-form-item label="手机号" class="item" prop="phone">
          <view class="phone-box" v-if="isBinded ==0">
            <view class="phone-btn">
              <button class="phoneBtn" size="mini" open-type="getPhoneNumber"
                        @getphonenumber="onGetPhoneNumber">一键绑定</button>
            </view>
          </view>
          <view class="phone-box" v-else>
            <view class="phone-txt">{{model.phone}}</view>
            <button class="phoneBtn" size="mini" open-type="getPhoneNumber"
                        @getphonenumber="onGetPhoneNumber">更换</button>
        </view>
      </h-form-item>
      <h-form-item label="人脸照片" class="item" prop="face_photo" >
        <image class="my-info-img" @tap="handlePhoto" :src="model.face_photo" v-if="model.face_photo"/>
        <image class="my-info-img" @tap="handlePhoto" src="https://pic4.58cdn.com.cn/nowater/lbgfe/image/n_v3479afa2e51fe4418a8a3666ff17a463d.png" v-else/>
      </h-form-item>
      <view class="sub">
        <button @tap="handleSave">提交</button>
      </view>
    </h-form>
    <h-toast></h-toast>
  </view>
</template>

<script>
/*import {
  request,
  requestData
} from '@/utils/http.js';
import uQRCode from '@/common/uqrcode.js'*/
import {
  request,
  requestData
} from '../../utils/http.js';
import Taro from "@tarojs/taro";
export default {
  name: 'myInfo',
  data() {
    return {
      model: {
        id: '',
        sex: '',
        nickName: '',
        phone: '',
        age: '',
        avatarUrl: '',
        face_photo: ''
      },
      rules: {
        'avatarUrl': [{
          required: true,
          message: '请上传头像',
        }],
        'nickName': [{
          required: true,
          message: '请填写姓名/昵称',
          trigger: 'blur'
        }],
        'sex': [{
          type: 'number',
          required: true,
          message: '请选择性别',
          trigger: 'change'
        }],
        'phone': [{
          required: true,
          message: '请绑定电话',
          trigger: 'change'
        }],
        'age': [{
          type: 'number',
          required: true,
          trigger: 'blur',
          asyncValidator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请填写年龄'))
            } else if (isNaN(Number(value))) {
              callback(new Error('年龄必须是数字类型，请重新填写'))
            } else {
              callback()
            }
          },
        }],
        face_photo: [
          {
            required: true,
            message: '请上传人脸照片',
            trigger: 'change'
          }
        ]
      },
      actions: [{
        label: '男',
        value: 1,
      },
        {
          label: '女',
          value: 2
        },
      ],
      showSex: false,
      isBinded: 0,
    }
  },
  onShow() {
    this.initUesrInfo()
  },
  methods: {
    //初始info
    initUesrInfo() {
      request('/user/info/get', {}).then(res => {
        let mobile = res?.datas?.mobile
        if(mobile) {
          this.isBinded = 1
        }
        this.model = {
          ...this.model,
          ...{
            id: res?.datas?.user_id || '',
            nickName: res?.datas?.nick_name,
            sex: res?.datas?.gender,
            age: res?.datas?.age || '',
            phone: res?.datas?.mobile || '',
            avatarUrl: res?.datas?.avatar_url || '',
          }
        }
        //这两项不从接口取，从缓存取
        if(res?.datas?.mobile) {
          Taro.setStorageSync('mobile_binded', 1);
        }
        Taro.setStorageSync('mobile', res?.datas?.mobile || '');
        Taro.setStorageSync('nickName', res?.datas?.nick_name || '昵称');
        Taro.setStorageSync('avatarUrl', res?.datas?.avatarUrl || '');

      }).catch(err => {
        console.log(err)
      })
    },

    onChooseAvatar(e) {
      Taro.setStorageSync('avatarUrl', e?.detail?.avatarUrl);
      this.model.avatarUrl = e?.detail?.avatarUrl

    },
    handleNickName(val) {
      this.model.nickName = val
    },
    onGetPhoneNumber(e) {
      const {
        detail: {
          encryptedData,
          iv,
          code
        }
      } = e;
      //console.log(e);
      if (e.detail.errMsg === "getPhoneNumber:ok") {
        let open_id = Taro.getStorageSync('open_id');
        let access_token = Taro.getStorageSync('access_token');
        request("/wxaccess/mp/user/getPhoneNumber", {
          "wxphone_code": code,
          'open_id': open_id
        }).then(res => {
          Taro.setStorageSync('open_id', res?.datas?.open_id || '');
          Taro.setStorageSync('user_id', res?.datas?.user_id || '');
          Taro.setStorageSync('access_token', res?.datas?.access_token || '');
          this.model.phone = res?.datas?.mobile
          this.isBinded = res?.datas?.mobile_binded;
        }).catch(err => {
          Taro.hToast({
            message: err
          })
        })
      } else {
        Taro.hToast({
          message: '为了给您提供更好的服务，请同意获取手机号！',
          duration: 2000,
        })
      }
    },
    handleCodeImg() {

    },
    handleImg() {

    },
    handleSave() {
      this.$refs.form.validate((valid) => {
        if (valid){
          request('/user/info/update', {
            gender: Number(this.model.sex),
            age: Number(this.model.age),
            nick_name: this.model.nickName,
            avatar_url: this.model.avatarUrl,
            mobile: this.model.phone
          }).then(res => {
            if (res.code == 0) {
              Taro.hToast({
                message: '保存成功',
              })
            } else {
              Taro.hToast({
                message: '保存失败',
              })
            }
          }).catch(err => {
            console.log(err)
          })
        }
        else console.log('校验失败');
      })
    },
    handlePhoto() {
      Taro.navigateTo({
        url: '/pages/takePhoto/index'
      })
    }
  }
}
</script>

<style lang="less">
.content {
  width: 100%;
  height: auto;
}

.vue-ref {
  width: 100%;
}

.u-form {
  width: 100%;
  height: auto;
  padding: 0 20px;
  box-sizing: border-box;
}

.right-pic {
  width: 60px;
  height: 60px;
}
.item-left {
  width: 30%;
  display: flex;
  align-items: center;
  padding-left: 20px;
  font-size: 28px;
}

.item-right {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  font-size: 14px;
}
.avatarUrl {
  border-radius: 50%;
  width: 60px;
  height: 60px;
}

.avatar-wrapper {
  padding: 0;
  width: 60px;
  height: 60px;
  border: 0;
  border-radius: 8px;
  outline: none;
  margin-left: 0;
}

.avatar {
  display: block;
  width: 100%;
  height: 100%;
}

.container {
  display: flex;
}

.phone-box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-left: 48rpx;
}

.sub {
  width: 100%;
  height: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 60px;
}

.sub button {
  border: none;
  width: 90%;
  height: 70px;
  line-height: 70px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #d5ad57;
  border-radius: 35px;
  color: #fff;
  font-size: 32px;
  font-weight: 400;
}

// .item-right-data {
// 	padding-right: 50px;
// }

.phone-txt {
  font-size: 28px;
}
.my-info-img {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
}
</style>
